package io.gitee.thant.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Base64;

public class SerializeUtil {
	private static final String noneObject = "<=+#*SerializeUtil_null*#+=>";
	
	public static boolean isValid(Object obj) {
		return obj != noneObject;
	}
	
	public static Object readObject(InputStream stm) {
		try (ObjectInputStream in = new ObjectInputStream(stm)) {
			return in.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return noneObject;
	}
	
	public static Object readObject(byte[] data) {
		ByteArrayInputStream stm = new ByteArrayInputStream(data);
		try (ObjectInputStream in = new ObjectInputStream(stm)) {
			return in.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return noneObject;
	}
	
	public static Object readObject(String data) {
		try {
			byte[] ba = Base64.getDecoder().decode(data);
			return readObject(ba);
		} catch (Exception e) {
			return noneObject;
		}
	}
	
	public static boolean writeObject(OutputStream stm, Object obj) {
		try (ObjectOutputStream out = new ObjectOutputStream(stm)) {
			out.writeObject(obj);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static boolean writeObject(StringBuilder sb, Object obj) {
		byte[] objstr = writeObject(obj);
		if (null == objstr) return false;
		
		sb.append(new String(Base64.getEncoder().encode(objstr)));
		return true;
	}

	//注意如果obj是null，返回值是一个有效的byte[]，而不是null
	public static byte[] writeObject(Object obj) {
		ByteArrayOutputStream stm = new ByteArrayOutputStream();
		try (ObjectOutputStream out = new ObjectOutputStream(stm)) {
			out.writeObject(obj);
			return stm.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
